﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using WebUI.SmartDatingRef;
using WebUI.SmsHostRef;
using SvcUtils;

namespace WebUI {
    public partial class Messages : BasePage {
        protected global::System.Web.UI.HtmlControls.HtmlInputButton cmdReload;
        protected global::System.Web.UI.HtmlControls.HtmlInputButton cmdSMS;

        protected void cmdDelete_ServerClick(object sender, EventArgs e) {
            ListViewDataItem item = (ListViewDataItem)((HtmlControl)sender).Parent.NamingContainer;
            int itemIndex = item.DataItemIndex;

            Object dataSource = ((ListView)item.NamingContainer).DataSource;
            Msg[] msgs = (Msg[])dataSource;

            Msg msg = msgs[itemIndex];

            Guid msgId = new Guid(Utils.GetMsgID(msg));
            OperationStatus resDelete = Client.DeletePM(SessionKeyHash, msgId);
            if (!Status.SUCCESS(resDelete)) {
                Utils.showError(errSpan, Status.m(resDelete));
            }

            Reload();
        }

        private string toValidPhoneNumber(string phoneNumber) {
            string tmp;
            if (phoneNumber.StartsWith("+")) {
                tmp = phoneNumber.Substring(1);
            } else if (phoneNumber.StartsWith("8")) {
                tmp = "7" + phoneNumber.Substring(1);
            } else {
                tmp = phoneNumber;
            }
            return tmp.Replace(" ", "");
        }

        protected void cmdSMS_ServerClick(object sender, EventArgs e) {
            // sms-host account data & sender name
            const string SMS_SERV_USER = "smart-dating";
            const string SMS_SERV_PASSWORD = "password";
            const string SMS_SERV_PHONE = "Info";
            // 2 days validity period
            const string VALIDITY_PERIOD = "000002233429000R";

            string templateText = txtSMS.Value;

            if (templateText.Trim().Length == 0) {
                Utils.showError(errSpan, "Пустой текст SMS.");
                return;
            }

            if (templateText.Length > 160) {
                Utils.showError(errSpan, "Слишком длинный текст SMS.<br/>Допустимая длина сообщения &mdash; не более 160 символов.");
            }

            using (SmsHostWsSoapClient smsHost = new SmsHostWsSoapClient()) {
                Authentication smsAuth = new Authentication() {
                                    User = SMS_SERV_USER,
                                    Password = SMS_SERV_PASSWORD
                                };
                List<WsSubmitSm> submits = new List<WsSubmitSm>();

                ResultWithStatusOfstring neighborRes =
                    Client.GetNeighborIds(SessionKeyHash);
                if (Status.SUCCESS(neighborRes.Status)) {
                    if (neighborRes.Result.Length == 0) return;
                    foreach (string id in neighborRes.Result.Split(',')) {
                        ResultWithStatusOfstring neighborPd = Client.GetForeignPersonalData(
                            SessionKeyHash, new Guid(id));
                        if (Status.SUCCESS(neighborPd.Status)) {
                            PersonalData pd = CryptoImpl.readObjectEncrypted<PersonalData>(
                                b(neighborPd.Result), b(SessionKey));
                            if (pd.phone_number != null) {
                                // found neighbor with a phone number, send SMS to him
                                string msgText = templateText.Replace("[]", pd.first_name + " " + pd.last_name);
                                submits.Add( new WsSubmitSm() { MessageText = msgText,
                                    SenderAddress = SMS_SERV_PHONE, ReceiverAddress = toValidPhoneNumber(pd.phone_number),
                                    ValidityPeriodSmpp = VALIDITY_PERIOD, MessageId = Guid.NewGuid() });
                            }
                        }
                    }
                }

                if (submits.Count > 0) {
                    WsSubmitSmResp submitResult;
                    try {
                        submitResult = smsHost.SumbitSm(smsAuth, submits.ToArray())[0];
                    } catch (Exception) {
                        Utils.showError(errSpan, "Не удалось разослать SMS.");
                        return;
                    }
                    if (submitResult.ErrorCode != 0) {
                        Utils.showError(errSpan, "Не удалось разослать SMS. <br />" + submitResult.ErrorDescription);
                    }
                }

            }
        }

        private void Reload() {
            ResultWithStatusOfArrayOfMsgswc4fAsa resMsgs =
                Client.GetPMs(SessionKeyHash, MessageFolder.Inbox);
            if (Status.SUCCESS(resMsgs.Status)) {
                lstInbox.DataSource = resMsgs.Result;
                lstInbox.DataBind();
            }

            ResultWithStatusOfArrayOfMsgswc4fAsa resSent =
                Client.GetPMs(SessionKeyHash, MessageFolder.Sent);
            if (Status.SUCCESS(resMsgs.Status)) {
                lstSentItems.DataSource = resSent.Result;
                lstSentItems.DataBind();
            }
        }

        protected void cmdReload_ServerClick(object sender, EventArgs e) {
            Reload();
        }

        protected void Page_Load(object sender, EventArgs e) {
            Utils.hideError(errSpan);

            Reload();
        }
    }
}